<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Byte Limit Input Example</title>
</head>
<body>
    <label for="byteLimitedInput">Enter text (max 32 bytes):</label>
    <input type="text" id="byteLimitedInput">
    <span id="byteCount">(0/32 bytes)</span>
 
    <script>
        const inputElement = document.getElementById('byteLimitedInput');
        const byteCountElement = document.getElementById('byteCount');
 
        function getByteLength(str) {
            // 使用TextEncoder将字符串转换为UTF-8字节数组，并返回其长度
            return new TextEncoder().encode(str).length;
        }
 
        inputElement.addEventListener('input', function() {
            let value = inputElement.value;
            let byteLength = getByteLength(value);
 
            // 如果字节长度超过32，截断字符串直到它符合限制
            while (byteLength > 32 && value.length > 0) {
                value = value.slice(0, -1); // 移除最后一个字符
                byteLength = getByteLength(value);
            }
 
            // 更新输入框的值和字节计数显示
            inputElement.value = value;
            byteCountElement.textContent = `(${byteLength}/32 bytes)`;
        });
    </script>
</body>
</html>